#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;

#define I(i,n) for (int i = 0; i < n; ++ i)

string _encode_str(const string & s) {
	string res = "\"";
	I(i, s.size()) {
		if (s[i]=='\"') res += "\\\"";
		else if (s[i]=='\\') res += "\\\\";
		else if (s[i]=='\n') res += "\\n";
		else res += s[i];
	}
	return res + "\"";
}

string _decode_str(const string & s) {
	string res = "";
	int n = s.size();
	I(i, n-1) {
		if (i==0) continue;
		if (s[i]=='\\') {
			++ i;
			char next = s[i];
			if (next=='\"') res += "\"";
			else if (next=='\\') res += "\\";
			else if (next=='n') res += "\n";
		}
		else res += s[i];
	}
	return res;
}

class WebData
{
	string _filename;
	vector<string> _keys;
	vector<string> _vals;

	int _index(const string & key) const {
		I(i, _keys.size())
			if (key == _keys[i]) return i;
		return -1;
	}

public:
	WebData(const string & filename) : _filename(filename) {
		ifstream fin(filename);
		vector<string> json;
		while (fin) {
			string line;
			getline(fin, line);
			json.push_back(line);
		}
		fin.close();
		decode_json(json);
	}

	string encode_json() const {
		stringstream ss;
		ss << "{";
		I(i, _keys.size()) {
			if (i!=0) ss << ",";
			ss << _encode_str(_keys[i]) << ":" <<  _encode_str(_vals[i]);
		}
		ss << "}";
		return ss.str();
	}

	void decode_json(const vector<string> & json) {
		I(i, json.size()) {
			const string & line = json[i];
			if (line=="{") continue;
			if (line=="}" or line=="{}") break;
			int index = line.find("\": \"");
			string k = _decode_str(line.substr(1, index));
			int len = line.size();
			len = (line[len-1]==',' ? len-1-(index+3) : len-(index+3));
			string v = _decode_str(line.substr(index+3, len));
			(*this)[k] = v;
		}
	}

	~WebData() {
		ofstream fout(_filename);
		fout << encode_json();
		fout.close();
	}

	const vector<string> & keys() const {
		return _keys;
	}

	bool has(const string & key) const {
		return _index(key)!=-1;
	}

	void del(const string & key) {
		int index = _index(key);
		if (index==-1) return;
		int n = _keys.size();
		swap(_keys[index], _keys[n-1]);
		swap(_vals[index], _vals[n-1]);
		_keys.pop_back();
		_vals.pop_back();
	}

	string get(const string & key) const {
		I(i, _keys.size())
			if (key == _keys[i]) return _vals[i];
		return "";
	}

	// 不要同时用于取值和赋值: e.g. v["x"] = v["y"], 
	//  因为当v["x"]导致push_back时, 可能使得v["y"]返回的引用被回收
	string & operator [] (const string & key) {
		int index = _index(key);
		if (index==-1) {
			_keys.push_back(key);
			_vals.push_back("");
			index = _keys.size()-1;
		}
		return _vals[index];
	}
	
};

WebData data("data.json");
